package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * 剑指 Offer 67. 把字符串转换成整数
 * 8. 字符串转换整数 (atoi)
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/1 12:38
 */
public class MyAtoi {
    public int myAtoi(String str) {
        byte[] bytes = str.getBytes();
        long i = 0L;
        boolean b = true;
        boolean c = true;
        for (byte sout : bytes) {
            if (sout == 45 || sout == 43 || sout == 32 || (sout <= 57 && sout >= 48)) {
                if (sout >= 48) {
                    i = i * 10 + sout - 48;
                    if (i > 2147483648L) {
                        break;
                    }
                    b = false;
                }
                if (sout == 45) {
                    if (b) {
                        c = false;
                        b = false;
                    } else {
                        break;
                    }
                }
                if (sout == 43) {
                    if (b) {
                        b = false;
                    } else {
                        break;
                    }
                }
                if (sout == 32) {
                    if (!b) {
                        break;
                    }
                }
            } else {
                break;
            }
        }
        if (!c) {
            i = i * (-1);
        }
        int j = 0;
        if (i > 2147483647L) {
            j = 2147483647;
        } else if (i < -2147483648L) {
            j = -2147483648;
        } else {
            j = (int) i;
        }
        return j;
    }

}
